package com.example.myapplication
import android.content.Context
import android.media.MediaPlayer
import android.widget.Toast
import androidx.core.content.edit
import androidx.core.net.toUri
import java.io.*
import androidx.compose.runtime.mutableStateListOf
import android.content.*
import android.os.IBinder
import androidx.core.content.ContextCompat

fun saveFileListToFile(context: Context, filename: String, files: List<File>) {
    val targetFile = File(context.filesDir, filename)
    targetFile.parentFile?.mkdirs()

    val tmpFile = File(context.filesDir, "$filename.tmp")
    tmpFile.parentFile?.mkdirs()

    FileOutputStream(tmpFile).use { fos ->
        DataOutputStream(fos).use { dos ->
            dos.writeLong(files.size.toLong())
            for (file in files) {
                val path = file.absolutePath
                val bytes = path.toByteArray(Charsets.UTF_8)
                dos.writeLong(bytes.size.toLong())
                dos.write(bytes)
            }
        }
    }
    tmpFile.renameTo(targetFile) // 原子替换
}

fun loadFileList(context: Context, filename: String, list: MutableList<File>) {
    list.clear()
    val file = File(context.filesDir, filename)
    if (!file.exists()) return

    try {
        FileInputStream(file).use { fis ->
            DataInputStream(fis).use { dis ->
                val count = dis.readLong()
                repeat(count.toInt()) {
                    val len = dis.readLong()
                    val buffer = ByteArray(len.toInt())
                    dis.readFully(buffer)
                    val path = String(buffer, Charsets.UTF_8)
                    list.add(File(path))
                }
            }
        }
    } catch (e: Exception) {
        android.util.Log.e("FileListIO", "加载失败: $filename", e)
    }
}

object MusicPlayerManager {
    private var musicService: PlaybackService? = null
    private var isBound = false

    // 服务连接回调
    private val connection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            val binder = service as PlaybackService.LocalBinder
            musicService = binder.getService()
            isBound = true
        }

        override fun onServiceDisconnected(arg0: ComponentName) {
            musicService = null
            isBound = false
        }
    }

    fun init(context: Context) {
        val intent = Intent(context, PlaybackService::class.java)

        // 使用 ContextCompat 自动处理版本兼容
        ContextCompat.startForegroundService(context, intent)

        // 绑定服务
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE)
    }

    fun play(index: Int) {
        if (isBound && musicService != null)
        {
            StaticStorage.playIndex = index
            musicService?.playAudio(index)
        }
    }

    fun play(context: Context, path: String) {
        // 尝试在 playList 中找到这个 path 对应的 index
        val index = StaticStorage.playList.indexOfFirst { it.absolutePath == path }
        if (index != -1) {
            play(index)
        } else {
        }
    }

    fun pause() {
        musicService?.player?.pause()
    }

    fun resume() {
        musicService?.player?.play()
    }

    // 上一首
    fun prev() {
        val list = StaticStorage.playList
        if (list.isEmpty()) return

        var newIndex = StaticStorage.playIndex - 1
        if (newIndex < 0) newIndex = list.size - 1 // 循环
        play(newIndex)
    }

    // 下一首
    fun next() {
        val list = StaticStorage.playList
        if (list.isEmpty()) return

        if (StaticStorage.playMode == PlayMode.SHUFFLE) {
            val newIndex = list.indices.random()
            play(newIndex)
        } else {
            var newIndex = StaticStorage.playIndex + 1
            if (newIndex >= list.size) newIndex = 0
            play(newIndex)
        }
    }

    fun release(context: Context) {
        if (isBound) {
            context.unbindService(connection)
            isBound = false
        }
        val intent = Intent(context, PlaybackService::class.java)
        context.stopService(intent)
    }

    // 获取当前播放进度 (用于 UI 更新)
    fun getCurrentPosition(): Long = musicService?.player?.currentPosition ?: 0L
    fun getDuration(): Long = musicService?.player?.duration ?: 0L
    fun isPlaying(): Boolean = musicService?.player?.isPlaying ?: false
    fun getCurrentIndex(): Int = StaticStorage.playIndex

    fun isLoaded(): Boolean = musicService?.isAudioLoaded() ?: true

    fun seekToRatio(ratio:Float)
    {
        musicService?.seekToRatio(ratio);
    }
}

object AccountManager
{
    private val AccountStorageFileName = "AccFile"

    var ActiveAccount: String = "";
    fun registerAccount(context: Context, account: String, passwordHash: Int)
    {
        if (account.isEmpty() || passwordHash == 0)
        {
            Toast.makeText(context, "账号或密码不得为空", Toast.LENGTH_SHORT).show();
            return;
        }
        val pref = context.getSharedPreferences(AccountStorageFileName, Context.MODE_PRIVATE)
        if (pref.getInt(account, 0) != 0)
        {
            Toast.makeText(context, "账号已存在", Toast.LENGTH_SHORT).show();
            return;
        }
        pref.edit { putInt(account, passwordHash) };
        Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT).show();
    }

    fun resetAccount(context: Context, passwordHash: Int)
    {
        val pref = context.getSharedPreferences(AccountStorageFileName, Context.MODE_PRIVATE)
        val account = pref.getString("ActiveAccount", "")
        if (account?.isEmpty() ?: true)
        {
            Toast.makeText(context, "你你你...你是怎么做到空账号登录的", Toast.LENGTH_SHORT).show()
            return;
        }
        if (passwordHash == 0)
        {
            Toast.makeText(context, "新密码不能为空", Toast.LENGTH_SHORT).show()
            return;
        }
        pref.edit { putInt(account, passwordHash) };
        Toast.makeText(context, "已重设密码", Toast.LENGTH_SHORT).show();
    }

    fun login(context: Context, account: String, passwordHash: Int, login:()-> Unit)
    {
        if (account.isEmpty() || passwordHash == 0)
        {
            Toast.makeText(context, "账号或密码不得为空", Toast.LENGTH_SHORT).show();
            return
        }
        val pref = context.getSharedPreferences(AccountStorageFileName, Context.MODE_PRIVATE)
        val get = pref.getInt(account, 0)
        if (passwordHash == get)
        {
            Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
            pref.edit { putString("ActiveAccount", account) }
            ActiveAccount = account;
            login();
        }
        else
        {
            Toast.makeText(context, "用户名或密码错误", Toast.LENGTH_SHORT).show()
        }
    }

    fun autoLogin(context: Context, login:()-> Unit)
    {
        if (StaticStorage.autoRuned)
        {
            return;
        }
        val pref = context.getSharedPreferences(AccountStorageFileName, Context.MODE_PRIVATE)
        ActiveAccount = pref.getString("ActiveAccount", "")?:"";
        if(ActiveAccount.isNotEmpty())
        {
            Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
            StaticStorage.autoRuned = true;

            login()
        }
    }

    fun logout(context: Context)
    {
        val pref = context.getSharedPreferences(AccountStorageFileName, Context.MODE_PRIVATE)
        pref.edit { putString("ActiveAccount", "") }
    }
}

enum class PlayMode {
    REPEAT_NONE,
    REPEAT_ONE,
    REPEAT_ALL,
    SHUFFLE,
    PLAY_ALL // 通常 PLAY_ALL 和 REPEAT_ALL 逻辑类似，或者播放完停止
}

object StaticStorage
{
    var autoRuned: Boolean = false;
    val musicList = mutableStateListOf<File>();
    var playList = mutableStateListOf<File>();
    val favouriteList = mutableStateListOf<File>();

    var playIndex = 0;
    var playMode = PlayMode.REPEAT_ALL;

    lateinit var Lib: File
}


